<script setup>
import {reactive} from "vue";
import {Search} from "@element-plus/icons-vue";
import request from "@/utils/request";
import {ElMessage, ElMessageBox} from "element-plus";

/**
 * 本地存储的账户信息
 *
 * @type {any}
 */
const account = JSON.parse(localStorage.getItem('account-info') || '{}')

/**
 * 是否是修改的判断
 *
 * @type {boolean}
 */
let isEdit = false

/**
 * 楼栋值
 *
 * @type {*[]}
 */
let buildingOptions = []

/**
 * 房间数据
 *
 * @type {UnwrapNestedRefs<{total: number, form: {roomNo: string, roomUpdateMan: string, roomCreateMan: string, roomUpdateTime: string, roomBuildingNo: string, roomCreateTime: string, roomName: string, roomBuildingName: string}, formVisible: boolean, pageSize: number, tableData: *[], pageNum: number, roomName: string}>}
 */
const roomData = reactive({
    roomName: '',
    tableData: [],
    total: 0,
    pageSize: 5,
    pageNum: 1,
    formVisible: false, // 是否显示弹窗
    form: {
        roomNo: '',
        roomName: '',
        roomBuildingNo: '',
        roomBuildingName: '',
        roomCreateMan: '',
        roomCreateTime: '',
        roomUpdateMan: '',
        roomUpdateTime: '',
    }
})

/**
 * 加载房间
 */
const loadRoom = () => {
    request.get(`/api/room/find-room-page`, {
        params: {
            pageNum: roomData.pageNum,
            pageSize: roomData.pageSize,
            roomName: roomData.roomName,
        }
    }).then(res => {
        roomData.tableData = res.data?.list || []
        roomData.total = res.data?.list.map(item => item.roomCountNumber)[0] || 0;
    })
}
// 调用房间加载方法，获取后台数据
loadRoom()

/**
 * 翻页
 */
const handelCurrentChange = () => {
    // 翻页时，重新加载数据即可
    loadRoom()
}

/**
 * 重置
 */
const reset = () => {
    roomData.roomName = ''
    // 重置时，重新加载数据即可
    loadRoom()
}

/**
 * 新增房间
 */
const addRoom = () => {
    isEdit = false
    // 清空上次残留的数据
    roomData.form = {}
    roomData.formVisible = true
}

/**
 * 加载楼栋
 */
const loadBuilding = () => {
    request.get(`/api/building/find-building`, {}).then(res => {
        buildingOptions = res.data
    })
}
// 调用学院加载方法，获取后台数据
loadBuilding()

/**
 * 提交新增的房间
 */
const submitAddRoom = () => {
    if (account.accountRoleName === 'visitor-admin') {
        ElMessage.info("游客-管理员仅可以查看信息")
    } else {
        roomData.form.roomCreateMan = account.accountNo
        request.post(`/api/room/add-room`, roomData.form).then(res => {
            if (res.code === "200") {
                // 重新获取数据
                loadRoom()
                // 关闭弹窗
                roomData.formVisible = false
                ElMessage.success("新增成功")
            } else {
                ElMessage.error(res.msg)
            }
        })
    }
}

/**
 * 修改房间
 *
 * @param row 按行修改
 */
const editRoom = (row) => {
    isEdit = true
    roomData.form = JSON.parse(JSON.stringify(row))
    roomData.formVisible = true
}

/**
 * 提交修改的房间
 */
const submitEditRoom = () => {
    if (account.accountRoleName === 'visitor-admin') {
        ElMessage.info("游客-管理员仅可以查看信息")
    } else {
        roomData.form.roomUpdateMan = account.accountNo
        request.put(`/api/room/update-room`, roomData.form).then(res => {
            if (res.code === "200") {
                // 重新获取数据
                loadRoom()
                // 关闭弹窗
                roomData.formVisible = false
                ElMessage.success("编辑成功")
            } else {
                ElMessage.error(res.msg)
            }
        })
    }
}

/**
 * 删除房间
 *
 * @param roomNo 房号
 */
const deleteRoom = (roomNo) => {
    ElMessageBox.confirm("删除数据后无法恢复，您确认删除此条数据？", "删除确认", {type: 'warning'}).then(res => {
        if (account.accountRoleName === 'visitor-admin') {
            ElMessage.info("游客-管理员仅可以查看信息")
        } else {
            request.delete(`/api/room/delete-room/${roomNo}`).then(res => {
                if (res.code === "200") {
                    // 重新获取数据
                    loadRoom()
                    ElMessage.success("删除成功")
                } else {
                    ElMessage.error(res.msg)
                }
            })
        }
    }).catch(() => {
        ElMessage({
            type: "info",
            message: "取消删除",
        })
    })
}
</script>

<template>
    <div v-if="account.accountRoleName === 'system-admin' || account.accountRoleName === 'visitor-admin'">
        <div class="card" style="margin-bottom: 10px;">
            <el-input style="width: 300px; margin-right: 10px;" v-model="roomData.roomName"
                      placeholder="请输入房间名称查询"
                      :prefix-icon="Search"/>
            <el-button @click="loadRoom" type="primary" style="margin-left: 10px;">查询</el-button>
            <el-button @click="reset" type="info">重置</el-button>
        </div>
        <div class="card" style="margin-bottom: 10px;">
            <div>
                <el-button @click="addRoom" type="primary" style="margin-bottom: 10px;">新增</el-button>
            </div>
            <div>
                <el-table :data="roomData.tableData" style="width: 100%">
                    <el-table-column prop="roomNo" label="房间号"/>
                    <el-table-column prop="roomName" label="房间名"/>
                    <el-table-column prop="roomBuildingName" label="楼栋名"/>
                    <el-table-column prop="roomCreateMan" label="创建人"/>
                    <el-table-column prop="roomCreateTime" label="创建时间"/>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button @click="editRoom(scope.row)" type="primary" size="small" plain>编辑
                            </el-button>
                            <el-button @click="deleteRoom(scope.row.roomNo)" type="danger" size="small"
                                       plain>删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="card">
            <el-pagination v-model:current-page="roomData.pageNum"
                           v-model:page-size="roomData.pageSize"
                           @current-change="handelCurrentChange"
                           background layout="prev, pager, next" :total="roomData.total"/>
        </div>

        <el-dialog v-model="roomData.formVisible" :close-on-click-modal="false" title="房间信息">
            <el-form :model="roomData.form" label-width="100px" label-position="right"
                     style="padding-right: 30px;" v-if="isEdit === false">
                <el-form-item label="房间号">
                    <el-input placeholder="请输入房间号" v-model="roomData.form.roomNo"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="房间名">
                    <el-input placeholder="请输入房间名" v-model="roomData.form.roomName" autocomplete="off"
                              :maxlength="30"></el-input>
                </el-form-item>
                <div class="block" style="margin-bottom: 20px; margin-left: 45px">
                    <el-select
                            v-model="roomData.form.roomBuildingNo"
                            class="m-2"
                            placeholder="请选择楼栋"
                            style="width: 525px"
                    >
                        <el-option
                                v-for="item in buildingOptions"
                                :key="item.buildingNo"
                                :label="item.buildingName"
                                :value="item.buildingNo"
                        />
                    </el-select>
                </div>
            </el-form>
            <el-form :model="roomData.form" label-width="100px" label-position="right"
                     style="padding-right: 30px;" v-if="isEdit === true">
                <el-form-item label="房间号">
                    <el-input placeholder="未填写" v-model="roomData.form.roomNo"
                              autocomplete="off" disabled></el-input>
                </el-form-item>
                <el-form-item label="房间名">
                    <el-input placeholder="请输入房间名" v-model="roomData.form.roomName" autocomplete="off"
                              :maxlength="30"></el-input>
                </el-form-item>
                <div class="block" style="margin-bottom: 20px; margin-left: 45px">
                    <el-select
                            v-model="roomData.form.roomBuildingNo"
                            class="m-2"
                            placeholder="请选择楼栋"
                            style="width: 525px"
                    >
                        <el-option
                                v-for="item in buildingOptions"
                                :key="item.buildingNo"
                                :label="item.buildingName"
                                :value="item.buildingNo"
                        />
                    </el-select>
                </div>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="roomData.formVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitAddRoom" v-if="isEdit === false">提交</el-button>
                    <el-button type="primary" @click="submitEditRoom" v-if="isEdit === true">提交</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>

</style>